<template>
    <div>
        <el-upload 
        ref="upload" 
        accept=".txt,.pdf"
        drag 
        action="" 
        :auto-upload="false" 
        multiple
        show-file-list
        >
            <i class="el-icon-upload"></i>
            <div class="el-upload__text">将文件拖到此处，或<em>点击选择</em></div>
        </el-upload>
        <el-button type="primary" @click="submit">开始上传</el-button>

        <el-dialog
            title="上传进度"
            :visible="dialog"
            append-to-body
            :close-on-click-modal="false"
            :close-on-press-escape="false"
            :show-close="false"
        >
            <el-progress :percentage="progress"></el-progress>
            <p style="text-align: center; margin: 10px 0">已上传大小：{{ loaded }}，总大小： {{ total }}</p>
        </el-dialog>
    </div>
</template>

<script>
import axios from 'axios'
export default {
    data() {
        return {
            dialog: false,
            loaded: 0,
            total: 0,
            progress: 0,
            fileList: []
        };
    },
    methods: {
        submit() {
            const files = this.$refs.upload.uploadFiles;
            if (files && files.length) {
                const fd = new FormData();
                files.forEach((item) => {
                    fd.append('files', item.raw, item.name);
                });
                console.log(files);
                console.log(fd);
                this.dialog = true;
                this.progress = this.loaded = this.total = 0;
                axios({
                    url: 'http://localhost:8443/api/v1/attachments/upload',
                    method: 'post',
                    onUploadProgress: (pe) => {
                        this.progress = Number.parseInt((pe.loaded / pe.total) * 100);
                        this.loaded = pe.loaded;
                        this.total = pe.total;
                    },
                    data: fd,
                    // headers: {
                    //     'Content-Type': 'multipart/form-data'
                    // }
                })
                    .then((res) => {
                        this.$message.success('上传成功');
                        this.$refs.upload.clearFiles();
                        this.dialog = false;
                    })
                    .catch((_) => {
                        this.$message.error('上传失败');
                        this.$refs.upload.clearFiles();
                        this.dialog = false;
                    });
            } else {
                this.$message.warning('至少选择一个文件');
            }
        }
    }
};
</script>

<style>
</style>